package com.simple.piger.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.simple.piger.dto.req.JobTitleReqDto;
import com.simple.piger.dto.resp.JobTitleRespDto;
import com.simple.piger.entity.JobTitle;
import com.simple.piger.mapper.JobTitleMapper;
import com.simple.piger.service.JobTitleService;
import com.simple.piger.utils.AjaxResult;
import com.simple.piger.utils.DateUtils;
import com.simple.piger.utils.IdUtil;
import com.simple.piger.utils.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 职位 服务实现类
 * </p>
 *
 * @author baolw
 * @since 2020-02-06
 */
@Service
public class JobTitleServiceImpl extends ServiceImpl<JobTitleMapper, JobTitle> implements JobTitleService {

    @Override
    public List<JobTitleRespDto> list(Integer page, Integer limit, Integer level) {
        List<JobTitleRespDto> list = this.baseMapper.list(PageUtil.getPageStart(page, limit), limit, level);
        for (JobTitleRespDto dto : list) {
            if (null != dto.getHotJob()) {
                String value = dto.getHotJob() == null ? null : dto.getHotJob() == 0 ? "否" : "是";
                dto.setHotJobValue(value);
            }
            dto.setCreateDate(DateUtils.dateFormat(dto.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        return list;
    }

    @Override
    public int count(Integer level) {
        EntityWrapper<JobTitle> ew = new EntityWrapper<>();
        ew.eq("level", level);
        int count = this.baseMapper.selectCount(ew);
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(JobTitleReqDto reqDto) {
        if (StringUtils.isNotBlank(reqDto.getId())) {
            JobTitle jobTitle = this.selectById(reqDto.getId());
            jobTitle.setName(reqDto.getName());
            jobTitle.setUpdateTime(new Date());
            jobTitle.setParentId(reqDto.getParentId());
            jobTitle.setHotJob(reqDto.getHotJob());
            jobTitle.updateById();
        } else {
            JobTitle jobTitle = new JobTitle();
            BeanUtils.copyProperties(reqDto, jobTitle);
            jobTitle.setId(IdUtil.getId());
            jobTitle.setLevel(reqDto.getLevel());
            jobTitle.setUpdateTime(new Date());
            jobTitle.setCreateTime(new Date());
            jobTitle.setDeleteFlag("0");
            jobTitle.insert();
        }
        return new AjaxResult(200, null);
    }
}
